﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebMobie.Models.Entities
{
	public class ShoppingCart
	{
		WebMobileContext storeDB;
		string ShoppingCartId { get; set; }
		public const string CartSessionKey = "CartId";
		public static ShoppingCart GetCart(WebMobileContext db)
		{
			var cart = new ShoppingCart(db);
			cart.ShoppingCartId = cart.GetCartId();
			return cart;
		}

		public ShoppingCart(WebMobileContext db)
		{
			storeDB = db;
		}

		public void AddToCart(Product product)
		{
			// Get the matching cart and album instances
			var cartItem = storeDB.Carts.SingleOrDefault(
			    c => c.CartId == ShoppingCartId
			    && c.Product.ProductId == product.ProductId);

			if (cartItem == null)
			{
				// Create a new cart item if no cart item exists
				cartItem = new Cart
				{
					Product = product,
					CartId = ShoppingCartId,
					Count = 1,
					DateCreated = DateTime.Now
				};
				storeDB.Carts.Add(cartItem);
			}
			else
			{
				// If the item does exist in the cart, 
				// then add one to the quantity
				cartItem.Count++;
			}
			// Save changes
			storeDB.SaveChanges();
		}
		public bool RemoveFromCart(int id)
		{
			// Get the cart
			var cartItem = storeDB.Carts.Single(
			    cart => cart.CartId == ShoppingCartId
			    && cart.RecordId == id);


			if (cartItem != null)
			{
				storeDB.Carts.Remove(cartItem);
				// Save changes
				storeDB.SaveChanges();
				return true;
			}
			return false;
		}

		public bool UpdateCart(int id, int num)
		{
			// Get the cart
			var cartItem = storeDB.Carts.Single(
			    cart => cart.CartId == ShoppingCartId
			    && cart.RecordId == id);


			if (cartItem != null)
			{
				if( num <= 0 )
					storeDB.Carts.Remove(cartItem);
				else
					cartItem.Count = num;
				// Save changes
				storeDB.SaveChanges();
				return true;
			}
			return false;
		}

		public void EmptyCart()
		{
			var cartItems = storeDB.Carts.Where(
			    cart => cart.CartId == ShoppingCartId);

			foreach (var cartItem in cartItems)
			{
				storeDB.Carts.Remove(cartItem);
			}
			// Save changes
			storeDB.SaveChanges();
		}
		public List<Cart> GetCartItems()
		{
			return storeDB.Carts.Where(
			    cart => cart.CartId == ShoppingCartId).ToList();
		}

		public static bool create_complete = false;
		public int GetCount()
		{
			if (create_complete == true)
			{
				// Get the count of each item in the cart and sum them up
				int? count = (from cartItems in storeDB.Carts
							  where cartItems.CartId == ShoppingCartId
							  select (int?)cartItems.Count).Sum();
				// Return 0 if all entries are null
				return count ?? 0;
			}
			else
			{
				create_complete = true;
				return 0;
			}

		}

		public int GetCountDistinct()
		{
			if (create_complete == true)
			{
				// Get the count of each item in the cart and sum them up
				int? count = (from cartItems in storeDB.Carts
							  where cartItems.CartId == ShoppingCartId
							  select cartItems).Count();
				// Return 0 if all entries are null
				return count ?? 0;
			}
			else
			{
				create_complete = true;
				return 0;
			}

		}

		public decimal GetTotal()
		{
			if (create_complete == true)
			{
				// Multiply album price by count of that album to get 
				// the current price for each of those albums in the cart
				// sum all album price totals to get the cart total
				decimal? total = (from cartItems in storeDB.Carts
								  where cartItems.CartId == ShoppingCartId
								  select (int?)cartItems.Count *
								  cartItems.Product.ActualCost).Sum();

				return total ?? decimal.Zero;
			}
			else
			{
				create_complete = true;
				return 0;
			}

		}
		public int CreateOrder(Order order)
		{
			decimal orderTotal = 0;

			var cartItems = GetCartItems();
			// Iterate over the items in the cart, 
			// adding the order details for each
			foreach (var item in cartItems)
			{
				var orderDetail = new OrderDetail
				{
					ProductId = item.Product.ProductId,
					Order = order,
					UnitCost = item.Product.ActualCost,
					Quantity = item.Count,
					SubTotal = item.Product.ActualCost * item.Count
				};
				// Set the order total of the shopping cart
				orderTotal += (item.Count * item.Product.ActualCost);

				storeDB.OrderDetails.Add(orderDetail);

			}
			// Set the order's total to the orderTotal count
			order.Total = orderTotal;

			// Save the order
			storeDB.SaveChanges();
			// Empty the shopping cart
			EmptyCart();
			// Return the OrderId as the confirmation number
			return order.Id;
		}
		// We're using HttpContextBase to allow access to cookies.
		public string GetCartId()
		{
			var session = HttpContext.Current.Session;
			if (session[CartSessionKey] == null)
			{
				// Generate a new random GUID using System.Guid class
				Guid tempCartId = Guid.NewGuid();
				// Send tempCartId back to client as a cookie
				session[CartSessionKey] = tempCartId.ToString();
			}
			return session[CartSessionKey].ToString();
		}
		// When a user has logged in, migrate their shopping cart to
		// be associated with their username
		public void MigrateCart(string userName)
		{
			var shoppingCart = storeDB.Carts.Where(
			    c => c.CartId == ShoppingCartId);

			foreach (Cart item in shoppingCart)
			{
				item.CartId = userName;
			}
			storeDB.SaveChanges();
		}
	}
}